/*
 * Copyright (C) 2012 Le Tuan Anh <anh.takaji@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package util;

import ezcms.dto.Role;
import ezcms.dto.User;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Le Tuan Anh <anh.takaji@gmail.com>
 */
public class RoleUtil {

    public static final String ROLE_ADMINISTRATOR = "Administrator";
    public static final String ROLE_PARTICIPANT = "Participant";
    public static final String ROLE_REVIEWER = "Reviewer";
    public static final String ROLE_GUEST = "Guest";

    public static boolean hasRole(User u, String role) {
        if (u != null && role != null) {
            for (Role r : u.getRoles()) {
                if (role.equals(r.getRoleName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void logout(HttpSession session) {
        session.setAttribute(ApplicationConstants.SESSION_USER, null);
    }

    public static boolean loggedIn(HttpSession session) {
        return session.getAttribute(ApplicationConstants.SESSION_USER) instanceof User;
    }

    public static boolean hasRole(HttpSession session, String role) {
        User u = (User) session.getAttribute(ApplicationConstants.SESSION_USER);
        return hasRole(u, role);
    }

    public static void login(HttpSession session, User autoLogin) {
        session.setAttribute(ApplicationConstants.SESSION_USER, autoLogin);
    }

    public static User whoami(HttpSession session) {
        return (User) session.getAttribute(ApplicationConstants.SESSION_USER);
    }
}
